import CryptoJS from 'crypto-js'
import gcoord from 'gcoord'
/**
 * 时间格式化。年：yyyy；月：M|MM；日：d|dd；时：h|hh；分：m|mm；秒：s|ss
 * @param {Date|String|Number} time 可以通过new Date转换成时间的数据
 * @param {String} pattern 年月日格式字符串。例：yyyy年MM月dd => 2010年05月25； yyyy-M-d => 2010-5-25
 */
export function formatTime(time, pattern) {
  const _pattern = pattern || 'yyyy-MM-dd hh:mm:ss'
  const date = new Date(time)
  if (date.toString() === 'Invalid Date') {
    // console.error('日期转换失败')
    return ''
  }
  const timeObj = {
    yyyy: date.getFullYear(),
    MM: `0${date.getMonth() + 1}`.slice(-2),
    M: date.getMonth() + 1,
    dd: `0${date.getDate()}`.slice(-2),
    d: date.getDate(),
    hh: `0${date.getHours()}`.slice(-2),
    h: date.getHours(),
    mm: `0${date.getMinutes()}`.slice(-2),
    m: date.getMinutes(),
    ss: `0${date.getSeconds()}`.slice(-2),
    s: date.getSeconds()
  }
  const timeStr = _pattern.replace(/(yyyy|MM|M|dd|d|hh|h|mm|m|ss|s)+/g, function(match, p) {
    const value = timeObj[p]
    return value
  })
  return timeStr
}

// 获取第一个链接
export function getFirstUrl(menu) {
  if (menu.length === 0) {
    return '/404'
  }
  if (menu.length > 0 && menu[0].children && menu[0].children[0].nodeType < 2) {
    return getFirstUrl(menu[0].children)
  } else {
    return menu[0].url
  }
}

export function isJSON(val) {
  if (typeof val !== 'string') {
    return false
  }
  try {
    const obj = JSON.parse(val)
    if (Object.prototype.toString.call(obj) === '[object Object]') {
      return true
    } else {
      return false
    }
  } catch (e) {
    return false
  }
}

export function deepClone(o, c) {
  const toString = Object.prototype.toString
  toString.call(o) === '[object Array]' ? c = c || [] : c = c || {}
  for (const i in o) {
    if (typeof o[i] === 'object' && o[i] !== null) {
      // 要考虑深复制问题了
      if (Array.isArray(o[i])) {
        // 这是数组
        c[i] = []
      } else {
        // 这是对象
        c[i] = {}
      }
      deepClone(o[i], c[i])
    } else {
      c[i] = o[i]
    }
  }
  return c
}

export function createDownloadLink(res = {}) {
  const downloadLink = window.document.createElement("a")
  const fileName = res.headers && res.headers.hasOwnProperty('content-disposition') && res.headers["content-disposition"].match(/filename="(.+)"/)[1]
  const fileUrl = res.data && window.URL.createObjectURL(res.data)
  downloadLink.href = fileUrl
  downloadLink.download = fileName
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
  window.URL.revokeObjectURL(fileUrl)
}

export function px2rem(px) {
  return (parseInt(px) / 100) + 'rem'
}

// 加密
export function encrypt(word, keyStr) {
  keyStr = keyStr || 'abcdefgabcdefg12'
  var key = CryptoJS.enc.Utf8.parse(keyStr)// Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

// 解密
export function decrypt(word, keyStr) {
  keyStr = keyStr || 'abcdefgabcdefg12'
  var key = CryptoJS.enc.Utf8.parse(keyStr)// Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

export function debounce(func, delay) {
  let timer

  return function(...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

export function getQueryString(name) {
  const href = window.location.href
  const reg = new RegExp(name + '=[^&|#|\/]*')
  const res = href.match(reg)
  return res ? href.match(reg)[0].split('=')[1] : ''
}

export function transformPoint(target, type = 'WGS84', targetType = 'AMap') {
  return gcoord.transform(target, gcoord[type], gcoord[targetType])
}